package com.higgins.law.server;

import java.io.InputStream;
import java.util.ArrayList;

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;

public class DocumentFactory {
	private GoogleDrive myGoogleDrive;
	private Drive drive ;
	
	public DocumentFactory() {
		try	{
			myGoogleDrive = new GoogleDrive();
			drive = myGoogleDrive.authenticate();
		} catch (Exception e)	{
		}
	}

	public void executeCoverLetterService()	{
//		  DocumentFactory documentFactory = new DocumentFactory();
		  try	{
			  GoogleSpreadsheetService gsService = new GoogleSpreadsheetService();
			  SpreadsheetService service = gsService.openService();
			  SpreadsheetEntry entry = gsService.openSpreadSheet(service, "LawFirmSheet");
			  ArrayList<ArrayList<String>> spreadsheetData = gsService.getSpreadsheetData(service, entry);
			  
			  for (ArrayList<String> list:spreadsheetData)	
				  createCoveringLetter("Hello.doc", list.get(0), list.get(1), list.get(2));
			  
		  }	catch (Exception e)	{
		  }		
	}
	
	public void createCoveringLetter(String templateFileName, String lawFirm, String address, String contact)	{
		  try {
				File originalFile = myGoogleDrive.getFile(drive, templateFileName);
				String originalFileTitle = originalFile.getTitle();
				String originalFileGoogleId = originalFile.getId();
				
				String duplicateFileTitle = myGoogleDrive.generateDuplicateFileName(originalFileTitle, lawFirm);
				
				File myDuplicateFile = GoogleDrive.copyFile(drive, originalFileGoogleId, duplicateFileTitle);

				InputStream inputStream = GoogleDrive.downloadWordFile(drive, myDuplicateFile);

				MSWordService myService = new MSWordService();
				java.io.File finalFile = myService.updateMSWordFile(inputStream, lawFirm, address, contact);
				
				GoogleDrive.updateFile(drive, myDuplicateFile, finalFile);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
}
